<template>
  <a-card :bordered='false'>
    <a-row type='flex' justify='space-between'>
      <div class='title'>文件上传下载测试</div>
    </a-row>
    <a-divider />
    <a-row :gutter="8">
      <a-col :span="6">
        <a-input v-model='fileName' placeholder='请输入文件名' />
      </a-col>
      <a-col :span="8">
        <a-button type='primary' @click='downloadFile'>下载文件</a-button>
      </a-col>
    </a-row>


    <a-divider />
    <a-row>
      <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload" >
        <a-button :disabled='fileList.length >= 1'> <a-icon type="upload" />选择文件 </a-button>
      </a-upload>
      <a-button
        type="primary"
        :disabled="fileList.length === 0"
        :loading="uploading"
        style="margin-top: 16px"
        @click="handleUpload"
      >
        {{ uploading ? '上传中' : '上传' }}
      </a-button>
    </a-row>
  </a-card>
</template>

<script>
import { fetchDownload, fetchUpload } from '@/utils/fetch'

export default {
  name: 'FileTest',
  data(){
    return {
      fileList: [],
      uploading: false,
      fileName:''
    }
  },
  methods:{
    downloadFile(){
      console.log('执行下载文件')
      fetchDownload("/test/download",{fileName:this.fileName})
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      console.log('file',file)
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload() {
      console.log('执行上传文件')
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('file', file);
      });
      formData.append('fileName', fileList[0].name.substring(0, fileList[0].name.lastIndexOf(".")));
      this.uploading = true;

      // You can use any AJAX library you like
      fetchUpload('/test/upload',formData).then((res)=>{
        console.log(res)
        this.$message.success('上传成功')
        this.uploading = false;
      }).catch((err)=>{
        console.log(err)
        this.$message.error('上传失败')
        this.uploading = false;
      })

    },
  }
}
</script>

<style scoped>
.title{
  font-size: 18px;
}

</style>